package com.oa.user.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.oa.organization.dao.OrganizationDao;
import com.oa.organization.entity.Organization;
import com.oa.system.dao.AccountDao;
import com.oa.system.dao.UserInfoDao;
import com.oa.system.entity.UserInfo;
import com.oa.user.dto.UserInfoDto;
import com.oa.util.SessionUtil;

@Service
@Transactional
public class UserManagerServiceImpl implements UserManagerService {
	@Resource
	private AccountDao accountDao;
	@Resource
	private UserInfoDao userInfoDao;
	@Resource
	private OrganizationDao organizationDao;

	@Resource
	private HttpServletRequest request;
	@Resource
	private HttpSession session;

	@Override
	public boolean deleteUser(Long id) {
		try {
			if (accountDao.exists(id)) {
				accountDao.delete(id);
			}
			if (userInfoDao.exists(id)) {
				UserInfo userInfo = userInfoDao.findOne(id);
				userInfo.setDept(null);
				userInfo.setRole(null);
				userInfoDao.save(userInfo);
				userInfoDao.delete(id);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean deleteUser(List<Long> ids) {
		try {
			ids.stream().forEach(id -> {
				if (accountDao.exists(id)) {
					accountDao.delete(id);
				}
				if (userInfoDao.exists(id)) {
					UserInfo userInfo = userInfoDao.findOne(id);
					userInfo.setDept(null);
					userInfo.setRole(null);
					userInfoDao.save(userInfo);
					userInfoDao.delete(id);
				}
			});
			return true;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	@Transactional(readOnly = true)
	public List<UserInfoDto> findByDeptId(Long deptId) {
		List<UserInfo> userInfos = userInfoDao.findByDeptId(deptId);
		List<UserInfoDto> userInfoDtos = new ArrayList<>();
		UserInfoDto userInfoDto;

		for (UserInfo userInfo : userInfos) {
			userInfoDto = UserInfoDto.toUserInfoDto(userInfo);
			userInfoDtos.add(userInfoDto);
		}

		return userInfoDtos;
	}

	@Override
	@Transactional(readOnly = true)
	public UserInfoDto getUserInfo(Long id) {
		UserInfo userInfo = userInfoDao.findOne(id);
		return UserInfoDto.toUserInfoDto(userInfo);
	}

	@Override
	@Transactional(readOnly = true)
	public UserInfo getUserInfo(String fullName) {
		return userInfoDao.findByFullname(fullName);
	}

	@Override
	@Transactional(readOnly = true)
	public Page<UserInfoDto> getUserInfoByQuery(UserInfoDto userInfoDto, Pageable pageable) {
		Organization organization = organizationDao.findByName(userInfoDto.getDept());
		userInfoDto.setOrganization(organization);

		Page<UserInfo> uPage = userInfoDao.findAll(UserInfoDto.getUserManagerQuery(userInfoDto), pageable);

		Page<UserInfoDto> userinfoDtoPage = uPage.map(new Converter<UserInfo, UserInfoDto>() {
			@Override
			public UserInfoDto convert(UserInfo source) {
				return UserInfoDto.toUserInfoDto(source);
			}
		});

		return userinfoDtoPage;
	}

	@Override
	@Transactional(readOnly = true)
	public Page<UserInfo> getAllUserInfo(Pageable pageable) {
		return userInfoDao.findAll(pageable);
	}

	@Override
	public boolean updateUserInfo(UserInfoDto userInfoDto) {
		UserInfo userInfo = userInfoDao.findOne(userInfoDto.getId());

		if (userInfo != null) {
			userInfo.setFullname(userInfoDto.getFullname());
			userInfo.setAddress(userInfoDto.getAddress());
			userInfo.setAge(userInfoDto.getAge());
			userInfo.setBirthday(userInfoDto.getBirthday());
			userInfo.setEmail(userInfoDto.getEmail());
			userInfo.setEnterTime(userInfoDto.getEnterTime());
			userInfo.setSex(userInfoDto.getSex());
			userInfo.setJob(userInfoDto.getJob());
			userInfo.setPhone(userInfoDto.getPhone());

			Organization organization = organizationDao.findOne(userInfoDto.getDeptId());
			userInfo.setDept(organization);

			userInfo = userInfoDao.save(userInfo);

			// 如果更新的是自己的用户信息，则更新Session上的用户信息
			if (SessionUtil.getUserId(session).equals(userInfo.getId())) {
				SessionUtil.setUserId(session, userInfo.getId());
				SessionUtil.setName(session, userInfo.getFullname());
				SessionUtil.setUserInfo(session, userInfo);
			}

			return true;
		} else {
			return false;
		}
	}

	@Override
	public void saveUserCover(MultipartFile multipartFile) throws IllegalStateException, IOException {
		String uploadPath = request.getSession().getServletContext().getRealPath("/") + "/upload";
		File file = new File(uploadPath);

		// 目录不存在便创建一个
		if (!file.exists()) {
			file.mkdir();
		}

		// 拼接文件名
		String username = SessionUtil.getUserName(request.getSession());
		String[] tmp = multipartFile.getOriginalFilename().split("\\.");
		String suffix = tmp[tmp.length - 1];
		String cover = username + "." + suffix;

		// 上传文件
		multipartFile.transferTo(new File(uploadPath, "/" + cover));

		// 保存文件名到用户信息中
		Long userId = SessionUtil.getUserId(request.getSession());
		UserInfo info = userInfoDao.findOne(userId);
		info.setCover(cover);
		info = userInfoDao.save(info);
		SessionUtil.setUserInfo(request.getSession(), info);
	}

}
